package model

import (
	"common/helper"
	"database/sql"
	"fmt"

	"encoding/json"
	g "github.com/doug-martin/goqu/v9"
	"time"
)

// app 自动升级配置
type AppUpgrade struct {
	ID          string `db:"id" json:"id"`
	Platform    string `db:"platform" json:"platform"`
	Version     string `db:"version" json:"version"`
	IsForce     uint8  `db:"is_force" json:"is_force"`
	Content     string `db:"content" json:"content"`
	URL         string `db:"url" json:"url"`
	UpdatedAt   uint32 `db:"updated_at" json:"updated_at"`
	UpdatedUid  string `db:"updated_uid" json:"updated_uid"`
	UpdatedName string `db:"updated_name" json:"updated_name"`
}

// 升级信息
type UpgradeInfo struct {
	Platform string `db:"platform" json:"platform"`
	Version  string `db:"version" json:"version"`
	IsForce  uint8  `db:"is_force" json:"is_force"`
	Content  string `db:"content" json:"content"`
	URL      string `db:"url" json:"url"`
}

// 更新升级配置
func AppUpgradeUpdate(recs AppUpgrade) error {

	ex := g.Ex{
		"id": recs.ID,
	}

	query, _, _ := dialect.Update("tbl_app_upgrade").Set(recs).Where(ex).ToSQL()

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	// 更新缓存
	AppUpgradeLoad()

	return nil
}

func AppUpgradeList() ([]AppUpgrade, error) {

	var data []AppUpgrade
	query, _, _ := dialect.From("tbl_app_upgrade").Select(colsAppUpgrade...).ToSQL()
	err := meta.MerchantDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(err, "数据库错误")
	}

	return data, nil
}

func AppUpgradeLoad() {

	var data []UpgradeInfo
	query, _, _ := dialect.From("tbl_app_upgrade").Select("platform", "version", "is_force", "content", "url").ToSQL()
	query = "/* master */ " + query

	err := meta.MerchantDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {
		return
	}

	pipe := meta.MerchantRedis.Pipeline()
	defer pipe.Close()

	for _, v := range data {
		key := fmt.Sprintf("upgrade:%s", v.Platform)

		resp := helper.Response{
			Status: true,
			Data:   v,
		}

		b, err := json.Marshal(resp)
		if err != nil {

			continue
		}

		pipe.Del(ctx, key)
		pipe.Set(ctx, key, b, 100*time.Hour)
		pipe.Persist(ctx, key)
	}

	_, err = pipe.Exec(ctx)
	if err != nil {

	}
}
